﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mani.Common.Security;
using RastinArgham.CRM.Business;
using Mani.Common;

namespace RastinArgham.CRM.Web
{
    public partial class list_provinces : System.Web.UI.Page
    {
       public ISecurityManager securityManager { get; set; }
       public CRMRepository crmRepository { get; set; }

       protected void Page_Load(object sender, EventArgs e)
       {
           if (securityManager == null)
           {
               securityManager = new SecurityManager();
               securityManager.authProvider = new WebAuthorizationProvider();
           }

           if (crmRepository == null)
               crmRepository = new CRMRepository();


           if (!securityManager.IsActionPermitted("provinces"))
               Response.Redirect("~/access_denied.aspx");

           if (!Page.IsPostBack)
               LoadProvinces();
       }

       private void LoadProvinces()
       {
           gvProvinces.DataSource = crmRepository.GetProvinces();
           gvProvinces.DataBind();
       }

       protected void gvProvinces_RowDeleting(object sender, GridViewDeleteEventArgs e)
       {
           string provinceId = gvProvinces.DataKeys[e.RowIndex].Value.ToString();
           crmRepository.DeleteProvince(Convert.ToInt32(provinceId));
           crmRepository.Save();
           LoadProvinces();
       }

       protected void gvProvinces_RowCreated(object sender, GridViewRowEventArgs e)
       {
           UIHelper.GridDeleteConfirm(e.Row);
       }

       protected void btnSave_Click(object sender, EventArgs e)
       {
           Province p = new Province();
           p.ProvinceName = txtProvinceName.Text;
           p.OperatorId = securityManager.authProvider.GetCurrentUser().UserId;
           crmRepository.AddProvince(p);
           crmRepository.Save();

           LoadProvinces();
           txtProvinceName.Text = String.Empty;
           UIHelper.ClientAlert(this, "تغییرات با موفقیت ذخیره شد");
       }
    }
}